<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: wlp.php 11 2013-09-21 11:43:11Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 11 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 11:43:11 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.');

define('MODULE_WLP_TEXT_DESCRIPTION', 'Export - Wir-lieben-Preise.de <br>(PIPE | getrennt)');
define('MODULE_WLP_TEXT_TITLE', 'Wir-lieben-Preise.de - TXT V1.1');
define('MODULE_WLP_FILE_TITLE' , '<hr noshade>Dateiname');
define('MODULE_WLP_FILE_DESC' , 'Geben Sie einen Dateinamen ein, falls die Exportdatei am Server gespeichert werden soll.<br>(Verzeichnis export/)');
define('MODULE_WLP_STATUS_DESC','Modulstatus');
define('MODULE_WLP_STATUS_TITLE','Status');
define('MODULE_WLP_CURRENCY_TITLE','W&auml;hrung');
define('MODULE_WLP_CURRENCY_DESC','Welche W&auml;hrung soll exportiert werden?');
define('EXPORT_YES','Nur Herunterladen');
define('EXPORT_NO','Am Server speichern');
define('MODULE_WLP_DELIVERY_COST_TITLE','<hr noshade><b>Versandkosten:</b>');
define('MODULE_WLP_DELIVERY_COST_DESC','Lassen Sie das Feld leer, wenn Sie die automatische Versandkostenanzeige in Ihrem Kundenkonto bei wir-lieben-preise.de aktiviert haben, ansonsten geben Sie hier die <b>Versandkosten als Bruttobetrag inkl. Steuer</b> ein (Format: Dezimaltrenner ist PUNKT), die f&uuml;r alle Artikel gelten soll. Die Eingabe von <b>0.00</b> bedeutet <b>versandkostenfrei</b>');
define('CURRENCY','<hr noshade><b>W&auml;hrung:</b>');
define('CURRENCY_DESC','W&auml;hrung in der Exportdatei');
define('EXPORT','Bitte den Sicherungsprozess AUF KEINEN FALL unterbrechen. Dieser kann einige Minuten in Anspruch nehmen.');
define('EXPORT_TYPE','<hr noshade><b>Speicherart:</b>');
define('EXPORT_STATUS_TYPE_WLP','<hr noshade><b>Kundengruppe:</b>');
define('EXPORT_STATUS_WLP','Bitte w&auml;hlen Sie die Kundengruppe, die die Basis f&uuml;r Produkte und den Preis bildet:</b>');
define('CAMPAIGNS','<hr noshade><b>Kampagnen:</b>');
define('CAMPAIGNS_DESC','Mit Kampagne zur Nachverfolgung verbinden.');

class wlp {
    var $code, $title, $description, $enabled, $db;

	function __construct() {
		global $order, $db;

		$this->code = 'wlp';
		$this->img = 'images/export/wirliebenpreise.gif';
		$this->title = MODULE_WLP_TEXT_TITLE;
		$this->description = MODULE_WLP_TEXT_DESCRIPTION;
		$this->sort_order = MODULE_WLP_SORT_ORDER;
		$this->enabled = ((MODULE_WLP_STATUS == 'True') ? true : false);
		$this->db = $db;
	}

    function process($file) {

	    @set_time_limit(0);
	    require(DIR_FS_CATALOG.DIR_WS_CLASSES . 'class.price.php');

	    //Kundengruppenpreise ermitteln
	    $price = new price($_POST['currencies'],$_POST['status'], $this->db);

		//Versandkosten, formattiert mit WР Т‘hrungsumrechnung
		if(isset($_POST['dlv']))
			if(is_numeric($_POST['dlv']))
				$deliverycost = number_format ($price->CalculateCurr($_POST['dlv']), 2, '.', '');

	    //SQL
	    $sql_query = " SELECT DISTINCT
                          pd.products_name,
                          pd.products_description,
                          p.products_price,
                          p.products_id,
                          p.products_image,
                          p.products_tax_class_id,
                          m.brand_name
                          FROM
                          ".TABLE_PRODUCTS." p LEFT JOIN ".TABLE_BRAND ." m ON p.brand_id = m.brand_id,
                          ".TABLE_PRODUCTS_DESCRIPTION." pd,
                          ".TABLE_PRODUCTS_TO_CATEGORIES." ptc,
                          ".TABLE_CATEGORIES." c
                          WHERE
                          p.products_id = ptc.products_id
                          AND
                          ptc.categories_id = c.categories_id
                          AND
                          p.products_status = '1'
                          AND
                          p.products_price > 0
                          AND
                          p.products_id = pd.products_id
                          AND
                          pd.language_id = '".$_SESSION['languages_id']."'
                          AND
                          c.categories_status = '1'
                          AND
                          p.products_fsk18 = '0' ";

		if(GROUP_CHECK == 'true')
			$group_check = "and p.group_permission_".$_POST['status']."=1 ";

		$sql_query.= $group_check." GROUP BY p.products_id";

		$products = $this->db->db_query($sql_query);

        while(!$products->EOF) {
			$products_price = $price->GetPrice($products->fields['products_id'], false, 1, $products->fields['products_tax_class_id']);

            $products_description = $this->rem_trash($products->fields['products_description'], "2");

			//Remove trash from name
			$products_name = $this->rem_trash(htmlentities(strip_tags($products->fields['products_name'])), "2");

			//get products image
			if(!empty($products->fields['products_image']))
				$image = HTTP_CATALOG_SERVER . DIR_WS_CATALOG_POPUP_IMAGES .$products->fields['products_image'];
			else
				$image = HTTP_CATALOG_SERVER . DIR_WS_CATALOG_POPUP_IMAGES .'no_pic.jpg';

			//Deeplink
			$deeplink =  HTTP_CATALOG_SERVER . DIR_WS_CATALOG . 'product_info.php?'.product_link($products->fields['products_id'], $products->fields['products_name']);
            if(!empty($_POST['campaign']))
				$deeplink.= '&'.$_POST['campaign'];

			//get brand
			if (empty($products->fields['brand_name']))
				$brand = '-';
			else
				$brand = $this->rem_trash($products->fields['brand_name'], "1");

            //create content
            if($products_price>0) {

              	$schema .=  $deeplink  . "|" .
                          substr($products_name, 0, 255) . "|".
                          $products_description ."|".
                          $image ."|" .
                          number_format ($products_price, 2, '.', '') ."|" .
                          substr($brand, 0, 255);

				if(isset($deliverycost) && is_numeric($deliverycost))
					$schema .= "|". $deliverycost ;

				$schema.=  "\n";

            }
			$products->MoveNext();
		}

		// create File
		$fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/' . $file, "w+");
		fputs($fp, $schema);
		fclose($fp);

		switch ($_POST['export']) {
		    case 'yes':
		        // send File to Browser
		        $extension = substr($file, -3);
		        $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/' . $file,"rb");
		        $buffer = fread($fp, filesize(DIR_FS_DOCUMENT_ROOT.'export/' . $file));
		        fclose($fp);
		        header('Content-type: application/x-octet-stream');
		        header('Content-disposition: attachment; filename=' . $file);
		        echo $buffer;
		        exit;

		    break;
        }
    }

    function display() {

    	$customers_statuses_array = get_customers_statuses();

    	$curr='';
	    $currencies = $this->db->db_query("SELECT code FROM ".TABLE_CURRENCIES);
	    while(!$currencies->EOF) {
	    	$curr.=draw_radio_field('currencies', $currencies_data->fields['code'],true).$currencies_data->fields['code'].'<br />';
	    	$currencies->MoveNext();
	    }

	    $campaign_array = array(array('id' => '', 'text' => TEXT_NONE));
		$campaign = $this->db->db_query("SELECT campaigns_name, campaigns_refID FROM ".TABLE_CAMPAIGNS." ORDER BY campaigns_id");

		while(!$campaign->EOF) {
			$campaign_array[] = array ('id' => 'refID='.$campaign->fields['campaigns_refID'].'&', 'text' => $campaign->fields['campaigns_name']);
			$campaign->MoveNext();
		}

	    return array('text' =>
	                        EXPORT_STATUS_TYPE_WLP.'<br>'.
	                        EXPORT_STATUS_WLP.'<br>'.
	                        draw_pull_down_menu('status',$customers_statuses_array, '1').'<br>'.
	                        CURRENCY.'<br>'.
	                        CURRENCY_DESC.'<br>'.
	                        $curr.
	                        MODULE_WLP_DELIVERY_COST_TITLE.'<br>'.
	                        draw_input_field('dlv', '').'<br>'.
	                        MODULE_WLP_DELIVERY_COST_DESC.'<br>'.
	                        CAMPAIGNS.'<br>'.
	                        CAMPAIGNS_DESC.'<br>'.
	                        draw_pull_down_menu('campaign',$campaign_array).'<br>'.
	                        EXPORT_TYPE.'<br>'.
	                        EXPORT.'<br>'.
	                        draw_radio_field('export', 'no',false).EXPORT_NO.'<br>'.
	                        draw_radio_field('export', 'yes',true).EXPORT_YES.'<br>'.
	                        '<br>' . button(BUTTON_EXPORT) .
	                        button_link(BUTTON_CANCEL, href_link(FILENAME_MODULE_EXPORT, 'set=' . $_GET['set'] . '&module=wlp')) . '<hr noshade>' .
	                        '&raquo; <a href="'.HTTP_CATALOG_SERVER . DIR_WS_CATALOG.'export/'.MODULE_WLP_FILE.'" style="font-weight:bold">Standardlink zur Exportdatei</a><br>');
    }

    function check() {
		if(!isset($this->_check)) {
			$check = $this->db->db_query("SELECT configuration_value from " . TABLE_CONFIGURATION . " WHERE configuration_key = 'MODULE_WLP_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
    }

    function install() {
		$this->db->db_query("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_WLP_FILE', 'wlp.txt',  '6', '1', '', now())");
		$this->db->db_query("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_WLP_STATUS', 'True',  '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
	}

    function remove() {
		$this->db->db_query("DELETE FROM " . TABLE_CONFIGURATION . " WHERE configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
		return array('MODULE_WLP_STATUS','MODULE_WLP_FILE');
    }


	function rem_trash($TextIn, $Modus) {
        /*
         Auslagerung und Anpassung durch DITH-Software / Thomas Huhn am 09.08.2006
         Р’В© DITH-Software
         KOntakt: Information@dith.de
         Diese Datei darf - sofern diese Information erhalten bleibt - uneingeschrР Т‘nkt weitergegeben werden.
         Wer Spenden mРЎвЂ chte darf das gerne per PayPal an Thomas.Huhn@dith.de tun *lol*
        */

       $Text = strip_tags($TextIn);

     	switch ($Modus) {

             case 1:    // alles soll weg
            $Text = str_replace("<br>"," ",$Text);
            $Text = str_replace("<br />"," ",$Text);
            $Text = str_replace(";",", ",$Text);
            $Text = str_replace("'",", ",$Text);
            $Text = str_replace("\n"," ",$Text);
            $Text = str_replace("\r"," ",$Text);
            $Text = str_replace(" | "," ",$Text);
            $Text = str_replace("\v"," ",$Text);
            $Text = str_replace("\\n"," ",$Text);
            $Text = str_replace("\\r"," ",$Text);
            // Kein Break, also auch den Rest erledigen

            case 2:   // Nicht alles lРЎвЂ schen
            $Text = str_replace("\n","<br>",$Text);
            $Text = str_replace("\r","<br>",$Text);
            $Text = str_replace("&quot,", chr(34),$Text);
            $Text = str_replace("&quot;", chr(34),$Text);
            $Text = str_replace("\\n","<br>",$Text);
            $Text = str_replace("\\r","<br>",$Text);
            $Text = str_replace("|",", ",$Text);
            $Text = str_replace("&nbsp,"," ",$Text);
            $Text = str_replace("&nbsp;"," ",$Text);
            $Text = str_replace("&amp,","&",$Text);
            $Text = str_replace("&amp;","&",$Text);
            $Text = str_replace("РІР‚С›","",$Text);

            // Umlaute
            $Text = str_replace("& uuml","ü",$Text);
            $Text = str_replace("& Auml","Ä",$Text);
            $Text = str_replace("& Uuml","Ü",$Text);
            $Text = str_replace("& auml","ä",$Text);
            $Text = str_replace("& Ouml","Ö",$Text);
            $Text = str_replace("& ouml","ö",$Text);
            $Text = str_replace("&uuml;","ü",$Text);
            $Text = str_replace("&auml;","ä",$Text);
            $Text = str_replace("&ouml;","ö",$Text);
            $Text = str_replace("&auml,","ä",$Text);
            $Text = str_replace("&uuml,","ü",$Text);
            $Text = str_replace("&ouml,","ö",$Text);
            $Text = str_replace("&Auml,","Ä",$Text);
            $Text = str_replace("&Uuml,","Ü",$Text);
            $Text = str_replace("&Ouml,","Ö",$Text);
            $Text = str_replace("&szlig;","ß",$Text);

            // Wenn Umlaute drin bleiben sollen dann diesen Block hier
            // mit /* und */ komplett auskommentieren
            /*
            $Text = str_replace("Р Т‘","ae",$Text);
            $Text = str_replace("РЎРЉ","ue",$Text);
            $Text = str_replace("РЎвЂ ","oe",$Text);
            $Text = str_replace("Р Р‡","ss",$Text);
            $Text = str_replace("Р вЂќ","Ae",$Text);
            $Text = str_replace("Р В¬","Ue",$Text);
            $Text = str_replace("Р В¦","Oe",$Text);
            */

            // bischen aufrР Т‘umen
            $Text = str_replace("<br><br>","<br>",$Text);
            $Text = str_replace("<br><br>","<br>",$Text);     // *lol*
            $Text = str_replace(",,",",",$Text);
            $Text = str_replace(chr(13)," ",$Text);
            $Text = substr($Text, 0, 65536);
            break;
        }
        return $Text;
	}
}
?>